package com.itheima.first;

import java.sql.*;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * 使用spring注入 dataSource，基于配置的演示
 * 优点：配置文件修改信息
 * 
 * @author weixingtk
 *
 */
public class DemoJDBC2 {


    public static void main(String[] args) {

    	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/itheima/first/beans01.xml");
	    DriverManagerDataSource dataSource = (DriverManagerDataSource)applicationContext.getBean("dataSource");
	     
        Connection conn = null;
        Statement stmt = null;
        try{
        
            // 打开链接
            System.out.println("连接数据库...");
            conn = dataSource.getConnection();
        
            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, username, balance FROM account";
            ResultSet rs = stmt.executeQuery(sql);
        
            // 展开结果集数据库
            while(rs.next()){
                // 通过字段检索
                int id  = rs.getInt("id");
                String username = rs.getString("username");
                Double balance = rs.getDouble("balance");
    
                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 用户名称: " + username);
                System.out.print(", 余额: " + balance);
                System.out.print("\n");
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
            // 处理 JDBC 错误
            se.printStackTrace();
        }catch(Exception e){
            // 处理 Class.forName 错误
            e.printStackTrace();
        }finally{
            // 关闭资源
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }

}
